package com.sgb.kjwl.viewmodel.self;

import android.app.Activity;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Base64;
import android.widget.Toast;

import com.chuanglan.shanyan_sdk.OneKeyLoginManager;




import com.sgb.kjwl.api.APIManager;

import com.sgb.kjwl.model.entity.LoginEntity;
import com.sgb.kjwl.model.entity.UserMsgEntity;
import com.sgb.kjwl.model.entity.user.OneKeyLoginEntity;
import com.sgb.kjwl.repository.SelfRepertory;
import com.sgb.kjwl.utils.MyLog;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LoginEvent;
import com.sgb.kjwl.view.ui.activity.MainActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.RegistrationWelcomeActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.SetPwdActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.link.entity.LoginEvents;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.model.entity.BaseEntity;
import com.im.immodel.IMUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.Date;

import cn.jpush.android.api.JPushInterface;
import retrofit2.Call;

public class VerificationCodeLoginModel3 extends BaseViewModel {
    private final SimpleDateFormat simpleDateFormat;
    private VerificationCodeLoginActivity activity;
    private SelfRepertory repertory;
    private String TAG = "VerificationCodeLoginModel3";

    public VerificationCodeLoginModel3(VerificationCodeLoginActivity activity, SelfRepertory repertory) {
        simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        this.activity = activity;
        this.repertory = repertory;
    }

    public void getCodeModel(String mobile) {
        APIManager.getInstance().getUserAPI().sendLoginSMS(mobile).enqueue(new ICallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity data) {
                if (data != null){
                    activity.starTime();
                    MToast.showToast(activity, data.getMsg() + "");
                }
            }
        });
    }

    public void loginModel(String mobile, String code) {
        activity.setEnable(false);
        APIManager.getInstance().getUserAPI().loginWithSMS(mobile, code,1).enqueue(new ICallBack<BaseEntity<LoginEntity>>(true, true) {
            @Override
            public void onSuccess(BaseEntity<LoginEntity> data) {
                if (data == null || data.getData() == null){
                    activity.setEnable(true);
                    return;
                }
                if (data.getData().isNeedRegister()){
                    Intent intent = new Intent(activity, SetPwdActivity.class);
                    intent.putExtra("mobile", data.getData().getPhone());
                    activity.startActivity(intent);
                    activity.finish();
                } else {
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_TOKEN, data.getData().getToken());
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PC_TOKEN, data.getData().getResourcePCToken());
                    loginImModel(data.getData(), mobile);
                }
            }

            @Override
            public void onFailure(Call<BaseEntity<LoginEntity>> call, Throwable t) {
                super.onFailure(call, t);
                activity.setEnable(true);
            }
        });
    }

    public void pwdLoginModel(String mobile, String pwd) {
        activity.setEnable(false);
        MyLog.e(TAG, "pwdLoginModel:START=" + simpleDateFormat.format(new Date(System.currentTimeMillis())));
        APIManager.getInstance().getUserAPI().login(mobile, Base64.encodeToString(pwd.getBytes(), Base64.DEFAULT)).enqueue(new ICallBack<BaseEntity<LoginEntity>>(true, true) {
            @Override
            public void onSuccess(BaseEntity<LoginEntity> data) {
                MyLog.e(TAG, "pwdLoginModel:STOP-onResponse=" + simpleDateFormat.format(new Date(System.currentTimeMillis())));
                if (data == null || data.getData() == null){
                    activity.setEnable(true);
                    return;
                }
                SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PC_TOKEN, data.getData().getResourcePCToken());
                loginImModel(data.getData(), mobile);
            }

            @Override
            public void onFailure(Call<BaseEntity<LoginEntity>> call, Throwable t) {
                super.onFailure(call, t);
                activity.setEnable(true);
            }
        });
    }

    //网易IM登陆
    private void loginImModel(LoginEntity loginEntity, String mobile) {
        MyLog.e(TAG, "loginImModel:START=" + simpleDateFormat.format(new Date(System.currentTimeMillis())));
        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.resourcePCToken, loginEntity.getResourcePCToken());
        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.resourceAPPToken, loginEntity.getResourceAPPToken());
//        NimUIKit.login(new LoginInfo(loginEntity.getImAccount(), loginEntity.getImToken()), new RequestCallback<LoginInfo>() {
//            @Override
//            public void onSuccess(LoginInfo param) {
                //DialogHelper.dismissProgressDialog();
                MyLog.e(TAG, "loginImModel:STOP-onResponse=" + simpleDateFormat.format(new Date(System.currentTimeMillis())));
                saveUserInfo(loginEntity);
                repertory.saveAccount(mobile);
                //保存IM登录信息
                saveIMLoginInfo(loginEntity);
                SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_TOKEN, loginEntity.getToken());
                SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PC_TOKEN, loginEntity.getResourcePCToken());
                SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PHONE, mobile);
                if (TextUtils.isEmpty(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.ISFRIIST,""))){
                SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.PERSON_AUTH, false);
                }
                activity.loginSucceed(loginEntity, mobile);
                JPushInterface.setAlias(activity, 1, mobile);
                if (activity.jump_address == EventConstant.EVENT_USER_CENTER_JUMP || activity.jump_address == EventConstant.EVENT_WEB_VIEW_JUMP) {
                    Toast.makeText(activity.getActivity(), "登录成功", Toast.LENGTH_SHORT).show();
                    if (activity.jump_address == EventConstant.EVENT_WEB_VIEW_JUMP){
                        getUserInfo(0);
                    }else {
                        getUserInfo(1);

                    }
                } else {
                    getUserInfo(0);
                }

//            }
//
//            @Override
//            public void onFailed(int code) {
//                MyLog.e(TAG, "loginImModel:STOP-onFailed=" + simpleDateFormat.format(new Date(System.currentTimeMillis())));
//                activity.setEnable(true);
//                //DialogHelper.dismissProgressDialog();
////                MToast.showToast(activity, "账号信息异常,请联系管理员!");
//                Toast.makeText(activity.getActivity(), "账号信息异常,请联系管理员!", Toast.LENGTH_SHORT).show();
//            }
//
//            @Override
//            public void onException(Throwable exception) {
//                MyLog.e(TAG, "loginImModel:STOP-onException=" + simpleDateFormat.format(new Date(System.currentTimeMillis())));
//                activity.setEnable(true);
//                //DialogHelper.dismissProgressDialog();
////                MToast.showToast(activity, "账号信息异常,请联系管理员!");
//                Toast.makeText(activity.getActivity(), "账号信息异常,请联系管理员!", Toast.LENGTH_SHORT).show();
//            }
//        });
    }

    private void saveIMLoginInfo(LoginEntity loginEntity) {
        IMUtils.getInstance().saveLoginUserInfo(loginEntity.getImAccount(), loginEntity.getToken(), loginEntity.getImToken(), loginEntity.getResourcePCToken(), loginEntity.getResourceAPPToken());
    }

    public void getUserInfo(int type) {
        MyLog.e(TAG, "getUserInfo:START=" + simpleDateFormat.format(new Date(System.currentTimeMillis())));
       APIManager.getInstance().getUserAPI().getUserInfo().enqueue(new ICallBack<BaseEntity<UserMsgEntity>>(true, true) {
           @Override
           public void onSuccess(BaseEntity<UserMsgEntity> data) {
               MyLog.e(TAG, "getUserInfo:STOP-onResponse=" + simpleDateFormat.format(new Date(System.currentTimeMillis())));
               if (data == null){
                   activity.setEnable(true);
                   Toast.makeText(activity, "获取用户信息失败", Toast.LENGTH_SHORT).show();
                   return;
               }
               if (data.getData() == null){
                   activity.setEnable(true);
                   return;
               }
               activity.getUserMsgSucceed(data.getData());
               repertory.saveNo(data.getData().getNo());
              /* if (data.getData().getEnterprise() != null) {
                   SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.SHOP_ID, data.getData().getEnterprise().getId());
                   SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.ENTERPRISE_NO, data.getData().getEnterprise().getNo());
               }*/
               //给SharedPreferenceUtil中的USER_NAME赋值 保存用户姓名
               SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.USER_NAME, data.getData().getUsername());
               //给SharedPreferenceUtil中的USER_NO赋值 保存用户ID
               SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.USER_NO, data.getData().getNo());
               //IM缓存用户No
               IMUtils.getInstance().saveIMUserId(data.getData().getNo(), data.getData().getRealName());
               //给SharedPreferenceUtil中的REAL_NAME赋值 保存实名认证的状态
               SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.REAL_NAME, data.getData().getRealName());
               SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.ENTERPRISE_AUTH, data.getData().isRelevance() ? "SUCCESS" : "NONE");
               SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.PERSON_AUTH, data.getData().getPersonalAuth() == 1 ? true : false);
               SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.ID_CARD, data.getData().getIdentityCard());
               SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.DRIVER_AUTH, data.getData().isDriverAuth() ? "SUCCESS" : "NONE");
               //保存是否关联企业 0未关联  1已关联
               SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.RELEVANCE, data.getData().isRelevance() ? "1" : "0");
               EventBus.getDefault().postSticky(LoginEvent.make(EventConstant.EVENT_MAIN_INDEX, 1));

              /* if (data.getData() != null && data.getData().getEnterprise() != null && !TextUtils.isEmpty(data.getData().getEnterprise().getNo())) {
                   SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.COMPANY_NAME, data.getData().getEnterprise().getCompanyName());
                   SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.COMPANY_NO, data.getData().getEnterprise().getNo());
                   //给SharedPreferenceUtil中的REAL_ID赋值 保存登录人ID
                   SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.REAL_ID, data.getData().getEnterprise().getId());
               }*/
               EventBus.getDefault().postSticky(LoginEvent.make(EventConstant.EVENT_LOGIN, "user"));
               EventBus.getDefault().postSticky(LoginEvents.make(EventConstant.EVENT_LOGIN, ""));
               if (!SharedPreferenceUtil.getInstance().getSaveBooleanData(SharedPreferenceUtil.PERSON_AUTH, true)){
                   RegistrationWelcomeActivity.start(activity,data.getData().getRealName());
               }
              if (type==1){
                  EventBus.getDefault().postSticky(LoginEvent.make(EventConstant.EVENT_LOGIN, "123"));
                  EventBus.getDefault().postSticky(LoginEvents.make(EventConstant.EVENT_LOGIN, ""));
                  activity.setResult(Activity.RESULT_OK);
                  activity.finish();
              }else {
                  if (activity.isJump) {
                      Intent intent = new Intent();
                      intent.putExtra("showPage", "FRAGMENT_SELF");
                      MainActivity.start(activity, intent);
                  } else {
                      activity.setResult(Activity.RESULT_OK);
                      activity.finish();

                  }

              }

               MyLog.e(TAG, "getUserInfo:STOP=" + simpleDateFormat.format(new Date(System.currentTimeMillis())));
               Toast.makeText(activity.getActivity(), "登录成功", Toast.LENGTH_SHORT).show();
           }

           @Override
           public void onFailure(Call<BaseEntity<UserMsgEntity>> call, Throwable t) {
               super.onFailure(call, t);
               MyLog.e(TAG, "getUserInfo:STOP-onFailure=" + simpleDateFormat.format(new Date(System.currentTimeMillis())));
               activity.setEnable(true);
           }
       });
    }

    private void saveUserInfo(LoginEntity loginEntity) {
        repertory.saveToken(loginEntity.getToken());
//        NimUIKit.setAccount(loginEntity.getImAccount());
//        AVChatKit.setAccount(loginEntity.getImAccount());
        //Preferences.saveUserAccount(loginEntity.getImAccount());
 //       Preferences.saveUserToken(loginEntity.getImToken());
    }


    public void oneKeyLogin(OneKeyLoginEntity oneKeyLoginEntity) {
        APIManager.getInstance().getUserAPI().oneClickLogin(oneKeyLoginEntity).enqueue(new ICallBack<BaseEntity<LoginEntity>>(true, true) {
            @Override
            public void onSuccess(BaseEntity<LoginEntity> data) {
                if (data == null || data.getData() == null){
                    return;
                }
                OneKeyLoginManager.getInstance().finishAuthActivity();
                if (data.getData().isNeedRegister()){
                    Intent intent = new Intent(activity, SetPwdActivity.class);
                    intent.putExtra("mobile", data.getData().getPhone());
                    activity.startActivityForResult(intent, 10);
                } else {
                    //登录成功逻辑
                    SharedPreferenceUtil.getInstance().cleatData();
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PC_TOKEN, data.getData().getResourcePCToken());
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_TOKEN, data.getData().getToken());
                    SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PHONE, data.getData().getPhone());
                    JPushInterface.setAlias(activity, 1, data.getData().getPhone());

                    loginImModel(data.getData(), data.getData().getPhone());
                }
            }
        });
    }
}
